package thread;

import java.util.ArrayList;
import java.util.Iterator;

import common.Utility;

public class ThreadManager 
{
	public ThreadManager() 
	{
		managedThreads = new ArrayList<ManagedThread>();
	}
	
	public static ThreadManager getInstance()
	{
		if (instance == null)
		{
			synchronized(ThreadManager.class)
			{
				if (instance == null)
				{
					instance = new ThreadManager();
				}
			}
		}
		
		return instance;
	}
	
	public boolean createThread(GameThread gameThread, boolean isTickThread)
	{
		if (gameThread == null)
		{
			assert(false);
			return false;
		}
		
		ManagedThread managedThread = new ManagedThread();
		managedThread.setTickThread(isTickThread);
		managedThread.setGameThread(gameThread);
		 
		Thread thread = new Thread(managedThread);
		thread.setName(gameThread.getThreadName());
		thread.start();
		
		managedThreads.add(managedThread);
		
		return true;
	}
	
	public void shutdown()
	{
		Iterator<ManagedThread> it = managedThreads.iterator();
		while (it.hasNext())
		{
			ManagedThread thread = it.next();
			thread.stop();
			
			while (thread.isRunning())
			{
				Utility.sleep(10);
			}
		}
	}
	 
	private static ThreadManager instance = null;
	private  ArrayList<ManagedThread> managedThreads;
}
